package cn.qu.dockman.mgr.controller;

import cn.qu.dockman.mgr.entity.Metrics;
import cn.qu.dockman.mgr.service.MetricsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * Created by zh on 17/3/21.
 */
@RestController
@RequestMapping("/metrics")
public class MetricsController {

    @Autowired
    private MetricsService metricsService;

    @RequestMapping(method = RequestMethod.GET)
    public List<Metrics> getMetricsDate(@RequestParam int size, @RequestParam int moId, @RequestParam(defaultValue = "") String start, @RequestParam String name) {
        PageInfo page = PageHelper.startPage(1, size)
                .doSelectPageInfo(() -> metricsService.findByName(name, moId, parseDate(start)));
        return Lists.reverse(page.getList());
    }

    private Date parseDate(String date) {
        try {
            if (!StringUtils.isBlank(date)) {
                return FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").parse(date);
            } else {
                return null;
            }
        } catch (ParseException e) {
            return null;
        }
    }
}
